<template>
  <div ref="chartRef" class="property-chart" :style="{ width: '100%', height: '400px', minWidth: '300px' }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { formatDate } from '@/utils/formatTime'

const props = defineProps({
  name: {
    type: String,
    default: ''
  },
  properties: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref()
let chartInstance = null
let retryCount = 0
let retryTimer = null
const MAX_RETRY_COUNT = 10

// 检查元素是否可见
const isElementVisible = (element) => {
  if (!element) return false
  
  const style = window.getComputedStyle(element)
  if (style.display === 'none' || style.visibility === 'hidden') {
    return false
  }
  
  // 检查元素是否在视口内
  const rect = element.getBoundingClientRect()
  if (rect.width === 0 || rect.height === 0) {
    return false
  }
  
  return true
}

// 初始化图表
const initChart = () => {
  // 清除之前的定时器
  if (retryTimer) {
    clearTimeout(retryTimer)
    retryTimer = null
  }
  
  if (chartRef.value) {
    // 检查元素是否可见
    if (!isElementVisible(chartRef.value)) {
      console.warn('[ECharts] Chart container is not visible, retrying...')
      if (retryCount < MAX_RETRY_COUNT) {
        retryCount++
        retryTimer = setTimeout(() => {
          initChart()
        }, 200)
      } else {
        console.error('[ECharts] Failed to initialize chart after maximum retries. Chart container is not visible.')
        retryCount = 0
      }
      return
    }
    
    // 确保DOM元素有尺寸
    if (chartRef.value.clientWidth === 0 || chartRef.value.clientHeight === 0) {
      console.warn('[ECharts] DOM width or height is 0, retrying...')
      // 增加重试次数限制和逐步增加的延迟时间
      if (retryCount < MAX_RETRY_COUNT) {
        retryCount++
        const delay = Math.min(100 * Math.pow(2, retryCount - 1), 1000) // 指数退避，最大1000ms
        retryTimer = setTimeout(() => {
          if (chartRef.value && chartRef.value.clientWidth > 0 && chartRef.value.clientHeight > 0) {
            doInitChart()
            retryCount = 0 // 成功后重置计数器
          } else {
            initChart() // 继续重试
          }
        }, delay)
      } else {
        console.error('[ECharts] Failed to initialize chart after maximum retries. DOM width or height is still 0.')
        retryCount = 0 // 重置计数器
      }
      return
    }
    
    doInitChart()
    retryCount = 0 // 成功后重置计数器
  }
}

// 实际初始化图表的函数
const doInitChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartRef.value)
  setChartOptions()
}

// 设置图表选项
const setChartOptions = () => {
  if (!chartInstance) return
  
  const option = {
    title: {
      text: props.name + '历史趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      name: '时间'
    },
    yAxis: {
      type: 'value',
      name: props.name
    },
    series: [
      {
        data: props.properties.map(item => [item.time, item.value]),
        type: 'line',
        smooth: true
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 窗口大小改变时重置图表尺寸
const resizeChart = () => {
  if (chartInstance) {
    // 确保DOM元素有尺寸
    if (chartRef.value && chartRef.value.clientWidth > 0 && chartRef.value.clientHeight > 0) {
      chartInstance.resize()
    }
  }
}

// 监听属性变化
watch(
  () => props.properties,
  () => {
    nextTick(() => {
      if (chartInstance) {
        setChartOptions()
      } else {
        initChart()
      }
    })
  },
  { deep: true }
)

// 监听窗口大小变化
let resizeObserver = null
onMounted(() => {
  // 使用 ResizeObserver 监听容器尺寸变化
  if (window.ResizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      resizeChart()
    })
    if (chartRef.value) {
      resizeObserver.observe(chartRef.value)
    }
  } else {
    window.addEventListener('resize', resizeChart)
  }
  
  // 初始化图表
  nextTick(() => {
    initChart()
  })
})

onBeforeUnmount(() => {
  // 清除定时器
  if (retryTimer) {
    clearTimeout(retryTimer)
    retryTimer = null
  }
  
  if (resizeObserver && chartRef.value) {
    resizeObserver.unobserve(chartRef.value)
  } else {
    window.removeEventListener('resize', resizeChart)
  }
  
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  retryCount = 0
})
</script>

<style scoped>
.property-chart {
  width: 100%;
  height: 400px;
  min-width: 300px;
}
</style>